package com.bw.park2301.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bw.lib_base.mvvm.BaseActivity
import com.bw.park2301.R
import com.bw.park2301.databinding.ActivityRegisterBinding
import dagger.hilt.android.AndroidEntryPoint
import java.util.Random

@AndroidEntryPoint
@Route(path = "/app/RegisterActivity")
class RegisterActivity : BaseActivity<ActivityRegisterBinding,UserViewModel>() {
    var code = ""
    override fun initView() {
        binding.sendCode.setOnClickListener {
            val uname = binding.etUsername.text.toString()
            if (uname.isNullOrEmpty()){
                ToastUtils.showLong("请先输入手机号")
                return@setOnClickListener
            }
            val format = String.format("%06d", Random().nextInt(100000))
            binding.etCode.setText(format)
            code = format
            Log.i("zhy", "获取到的验证码是: " + code)
        }
        binding.btnRegister.setOnClickListener {
            val uname = binding.etUsername.text.toString()
            val code1 = binding.etCode.text.toString()
            val pwd = binding.etPassword.text.toString()
            val repwd = binding.etRepassword.text.toString()
            if (pwd.isNullOrEmpty()){
                ToastUtils.showLong("请先输入密码")
                return@setOnClickListener
            }
            //正则 1[0-9]{10}
            if (!uname.matches(Regex("[A-z0-9_]{6,16}"))){
                ToastUtils.showLong("不是合法用户名，请输入至少6位的数字、字母、符号")
                return@setOnClickListener
            }
            if (code1.isNullOrEmpty()){
                ToastUtils.showLong("请先输入验证码")
                return@setOnClickListener
            }
            if (!code1.equals(code)){
                ToastUtils.showLong("验证码输入有误")
                return@setOnClickListener
            }
            if (!pwd.equals(repwd)){
                ToastUtils.showLong("两次密码输入不一致")
                return@setOnClickListener
            }
            viewModel.register(pwd,uname)
        }

        binding.goLogin.setOnClickListener {
            ARouter.getInstance().build("/app/LoginActivity").navigation()
            finish()
        }

        binding.tvv.setOnClickListener {
            ARouter.getInstance().build("/app/WebViewActivity").navigation()
        }
    }

    override fun initData() {
        viewModel.registerData.observe(this){
            Log.i("zhy", it.toString())
            finish()
        }
    }
}